<template>
  <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
    <!-- 公共字段 -->
    <el-form-item label="客户" prop="customer_id">
      <el-select v-model="form.customer_id" placeholder="请选择客户" filterable style="width: 100%">
        <el-option
          v-for="item in customerOptions"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>
    </el-form-item>

    <el-form-item label="订单标题" prop="title">
      <el-input v-model="form.title" placeholder="请输入订单标题" />
    </el-form-item>

    <el-form-item label="订单金额" prop="amount">
      <el-input-number v-model="form.amount" :min="0" :precision="2" style="width: 100%" />
    </el-form-item>

    <el-form-item label="付款方式" prop="payment_type">
      <el-select v-model="form.payment_type" placeholder="请选择付款方式" style="width: 100%">
        <el-option
          v-for="item in paymentMethodOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
    </el-form-item>

    <el-form-item label="付款计划">
      <el-input
        v-model="form.payment_plan"
        type="textarea"
        :rows="2"
        placeholder="请输入付款计划，如：首付30%，尾款70%"
      />
    </el-form-item>

    <el-form-item label="订单描述">
      <el-input v-model="form.description" type="textarea" :rows="4" placeholder="请输入订单描述" />
    </el-form-item>

    <el-form-item label="合同文件">
      <el-upload
        ref="uploadRef"
        action=""
        :auto-upload="false"
        :on-change="handleFileChange"
        :on-remove="handleFileRemove"
        :file-list="form.contract_files"
        multiple
        accept=".pdf,.doc,.docx,.jpg,.jpeg,.png"
        list-type="picture-card"
      >
        <el-icon><Plus /></el-icon>
        <template #file="{ file }">
          <div>
            <img
              v-if="file.url && isImage(file.name)"
              :src="file.url"
              alt="文件预览"
              class="el-upload-list__item-thumbnail"
            />
            <el-icon v-else class="el-upload-list__item-icon"><Document /></el-icon>
            <span class="el-upload-list__item-name">{{ file.name }}</span>
            <el-button type="text" size="small" @click.stop="previewFile(file)">预览</el-button>
            <el-button type="text" size="small" @click.stop="removeFile(file)">删除</el-button>
          </div>
        </template>
      </el-upload>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue'
  import { ElUpload } from 'element-plus'
  import { Plus, Document } from '@element-plus/icons-vue'
  import { orderApi, customerApi } from '@/api/crm'
  import type { UploadUserFile } from 'element-plus'

  // Props定义
  const props = defineProps({
    customerId: {
      type: Number,
      default: 0,
    },
    orderData: {
      type: Object,
      default: () => ({}),
    },
  })

  // Emits定义
  const emit = defineEmits(['update:form-data'])

  // 表单引用
  const formRef = ref()
  const uploadRef = ref<InstanceType<typeof ElUpload>>()

  // 表单数据
  const form = reactive({
    customer_id: props.customerId || 0,
    order_type: 1,
    order_category: 1,
    title: '',
    amount: 0,
    contract_no: '',
    payment_type: 1,
    payment_plan: '',
    description: '',
    contract_files: [] as UploadUserFile[],
  })

  // 表单验证规则
  const rules = {
    customer_id: [{ required: true, message: '请选择客户', trigger: 'change' }],
    title: [{ required: true, message: '请输入订单标题', trigger: 'blur' }],
    amount: [{ required: true, message: '请输入订单金额', trigger: 'blur' }],
    payment_type: [{ required: true, message: '请选择付款方式', trigger: 'change' }],
  }

  // 选项数据
  const customerOptions = ref<Array<{ id: number; name: string }>>([])
  const paymentMethodOptions = ref<Array<{ value: string; label: string }>>([])

  // 初始化数据
  const initData = () => {
    // 如果有传入订单数据，则填充表单
    if (Object.keys(props.orderData).length > 0) {
      Object.keys(form).forEach(key => {
        if ((props.orderData as any)[key] !== undefined) {
          ;(form as any)[key] = (props.orderData as any)[key]
        }
      })
    }
  }

  // 获取选项数据
  const getOptions = async () => {
    try {
      const [customerRes, paymentMethodRes] = await Promise.all([
        customerApi.getCustomerOptions(),
        orderApi.getPaymentMethodOptions(),
      ])
      // 过滤并处理可能的空值，确保id始终有效
      customerOptions.value = customerRes.data
        .filter((item: { value: any }) => item.value !== undefined && item.value !== null)
        .map((item: { value: string | number; label: string }) => ({
          id: item.value,
          name: item.label,
        }))
      // 同样处理paymentMethodOptions，确保value属性有效
      paymentMethodOptions.value = paymentMethodRes.data.filter(
        (item: { value: any }) => item.value !== undefined && item.value !== null
      )
    } catch (error) {
      console.error('获取选项失败:', error)
      // 错误时确保选项数组为空数组，而不是undefined
      customerOptions.value = []
      paymentMethodOptions.value = []
    }
  }

  // 检查是否为图片文件
  const isImage = (fileName: string): boolean => {
    const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.webp']
    const extension = fileName.toLowerCase().substr(fileName.lastIndexOf('.'))
    return imageExtensions.includes(extension)
  }

  // 处理文件变化
  const handleFileChange = (file: UploadUserFile) => {
    // 这里可以添加文件验证逻辑
  }

  // 处理文件移除
  const handleFileRemove = (file: UploadUserFile) => {
    // 移除文件逻辑
  }

  // 预览文件
  const previewFile = (file: UploadUserFile) => {
    // 预览文件逻辑
  }

  // 移除文件
  const removeFile = (file: UploadUserFile) => {
    const index = form.contract_files.findIndex(item => item.uid === file.uid)
    if (index !== -1) {
      form.contract_files.splice(index, 1)
    }
  }

  // 重置表单
  const resetForm = () => {
    form.customer_id = props.customerId || 0
    form.title = ''
    form.amount = 0
    form.contract_no = ''
    form.payment_type = 1
    form.payment_plan = ''
    form.description = ''
    form.contract_files = []
  }

  // 获取表单数据
  const getFormData = () => {
    return { ...form }
  }

  // 监听表单数据变化，通知父组件
  const watchFormChanges = () => {
    emit('update:form-data', { ...form })
  }

  // 暴露方法给父组件
  defineExpose({
    initData,
    resetForm,
    getFormData,
    formRef,
    watchFormChanges,
  })

  // 组件挂载时初始化
  onMounted(() => {
    getOptions()
    if (Object.keys(props.orderData).length > 0) {
      initData()
    }
  })
</script>

<style scoped>
  /* 可以添加特定样式 */
</style>
